<template>
  <el-upload
    action="#"
    list-type="picture-card"
    class="file-uploader"
    :multiple="false"
    :on-preview="handlePreview"
    :http-request="handleHttpUpload"
  >
    <div class="file-upload-trigger">
      <el-icon><Plus /></el-icon>
    </div>
  </el-upload>
</template>

<script lang="ts" setup>
import { uploadImg, uploadVideo } from "@/api/modules/upload";
import type { UploadRequestOptions, UploadFile } from "element-plus";
import { ref } from "vue";

const props = defineProps({
  type: String,
  multiple: Boolean
});

const uploadedFiles = ref([] as Array<{ uid: number; urlPath: string }>);

defineExpose({
  uploadedFiles
});

const handleHttpUpload = async (options: UploadRequestOptions) => {
  let formData = new FormData();
  formData.append("file", options.file);
  console.log(options.file);
  try {
    let uploader = (formData: any): any => {
      console.log(formData);
    };
    if (props.type == "video") {
      uploader = uploadVideo;
    } else {
      uploader = uploadImg;
    }
    const { data } = await uploader(formData);
    const { urlPath } = data;
    uploadedFiles.value.push({ uid: options.file.uid, urlPath });
  } catch (error) {
    options.onError(error as any);
  }
};

const handlePreview = (uploadFile: UploadFile) => {
  let f = uploadedFiles.value.filter(f => f.uid == uploadFile.uid)[0];
  window.open(f.urlPath, "_blank");
};
</script>

<style lang="scss" scoped>
.file-uploader {
  display: flex;
}
.file-upload-trigger {
  width: 148px;
  height: 148px;
  display: block;
  font-size: 28px;
  color: #8c939d;
  text-align: center;
  line-height: 148px;
  // border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  transition: var(--el-transition-duration-fast);
  &:hover {
    cursor: pointer;
    border-color: var(--el-color-primary);
  }
}
</style>
